#include "opedb.h"
#include <QMessageBox>
#include <QDebug>
#include <QSqlError>

OpeDB::OpeDB(QObject *parent)
    : QObject{parent}
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
}

OpeDB &OpeDB::getInstance()
{
    static OpeDB instance;
    return instance;
}

void OpeDB::init()
{
    m_db.setHostName("localhost");
    m_db.setDatabaseName("E:/qt_code/Online_disk/TcpServer/cloud.db");
    if(m_db.open()) {
        // 查询测试
        QSqlQuery query;
        query.exec("select * from usrInfo");
        while(query.next()) {
            QString data = QString("%1,%2,%3").arg(query.value(0).toString()).arg(query.value(1).toString()).arg(query.value(2).toString());
            qDebug() << "Data: " << data;
        }
    }else {
        QMessageBox::critical(NULL,"打开数据库","打开数据库失败");
    }
}

OpeDB::~OpeDB()
{
    m_db.close();
}

// 处理注册
bool OpeDB::handleRegist(const char *name, const char *pwd)
{
    if(NULL == name || NULL == pwd){
        qDebug() << "name | pwd is NULL";
        return false;
    }
    QString data = QString("insert into usrInfo(name,pwd) values(\'%1\',\'%2\')").arg(name).arg(pwd);
    qDebug() << data;
    QSqlQuery query;
    return query.exec(data);
}

// 处理登录
bool OpeDB::handleLogin(const char *name, const char *pwd)
{
    // 1.参数校验
    if(NULL == name || NULL == pwd){
        qDebug() << "name | pwd is NULL";
        return false;
    }

    // 2.查询登录状态
    QString data = QString("select * from usrInfo where name = \'%1\' and pwd = \'%2\' and online = 0").arg(name).arg(pwd);
    qDebug() << data;
    QSqlQuery query;
    query.exec(data);
    if(query.next()) {
        QString data = QString("update usrInfo set online = 1 where name = \'%1\' and pwd = \'%2\'").arg(name).arg(pwd);
        qDebug() << data;
        QSqlQuery query;
        query.exec(data);
        return true;
    }else {
        return false;
    }
}

// 处理下线
void OpeDB::handleOffline(const char *name)
{
    // 1.参数校验
    if(NULL == name){
        qDebug() << "name is NULL";
    }

    // 2.查询登录状态
    QString data = QString("update usrInfo set online = 0 where name = \'%1\'").arg(name);
    qDebug() << data;
    QSqlQuery query;
    query.exec(data);
}

// 获取所有在线用户
QStringList OpeDB::handleAllOnline()
{
    QString data = QString("select name from usrInfo where online = 1");
    qDebug() << data;
    QSqlQuery query;
    query.exec(data);

    QStringList result;
    result.clear();

    while(query.next()) {
        result.append(query.value(0).toString());
    }
    return result;
}

// 根据用户名查找用户
int OpeDB::handleSearchUsr(const char *name)
{
    if(NULL == name) {
        return -1;
    }
    QString data = QString("select online from usrInfo where name = \'%1\'").arg(name);
    QSqlQuery query;
    query.exec(data);

    if(query.next()) {
        int ret = query.value(0).toInt();
        if(ret == 1) {
            return 1;
        }else if(0 == ret) {
            return 0;
        }
    }
    return -1;
}

// 处理添加好友请求
int OpeDB::handleAddFriend(const char *pername, const char *name)
{
    if(pername == NULL || name == NULL) {
        return -1; // 传参校验
    }
    QString data = QString("select * from friend where "
                           "(id = (select id from usrInfo where name = \'%1\') and friendId = (select id from usrInfo where name = \'%2\')) "
                           "or (id = (select id from usrInfo where name = \'%3\') and friendId = (select id from usrInfo where name = \'%4\'))")
                       .arg(pername).arg(name).arg(name).arg(pername);
    qDebug() << data;
    QSqlQuery query;
    query.exec(data);

    if(query.next()) {
        return 0; // 双方已经是好友
    } else {
        QString data = QString("select online from usrInfo where name = \'%1\'").arg(pername);
        QSqlQuery query;
        query.exec(data);

        if(query.next()) {
            int ret = query.value(0).toInt();
            if(ret == 1) {
                return 1; // 在线
            }else if(0 == ret) {
                return 2; // 不在线
            }
        }
    }

    return 3; // 不存在该用户
}

// 添加好友入库
bool OpeDB::addFriendPersistence(const char *pername, const char *name)
{
    if(pername == NULL || name == NULL) {
        return false;
    }

    QString userName1 = name;
    QString userName2 = pername;

    QString data = "INSERT INTO friend(id, friendId) "
                   "values ((SELECT id FROM usrInfo WHERE name = :userName1), "
                   "(SELECT id FROM usrInfo WHERE name = :userName2))";
    QSqlQuery query;
    query.prepare(data);
    query.bindValue(":userName1", userName1);
    query.bindValue(":userName2", userName2);
    if(query.exec()) {
        qDebug() << "插入成功,插入的行ID：" << query.lastInsertId();
        return true;
    }else {
        qDebug() << "插入失败：" <<  query.lastError().text();
        return false;
    }
}

QStringList OpeDB::handleFlushFriend(const char *name)
{
    QString selfName = name;
    QStringList strFriendList;
    strFriendList.clear();

    if(NULL == name) {
        return strFriendList;
    }

    QString data = QString("select name from usrInfo where id in "
                           "(select id from friend where friendId = (select id from usrInfo where name = :selfName) "
                           "union select friendId from friend where id = (select id from usrInfo where name = :selfName))");
    QSqlQuery query;
    query.prepare(data);
    query.bindValue(":selfName", selfName);
    query.exec();
    while(query.next()) {
        strFriendList.append(query.value(0).toString());
    }
    foreach(const QString &friendName, strFriendList){
        qDebug() << friendName;
    }
    return strFriendList;
}

bool OpeDB::handleDelFriend(const char *selfname, const char *friendName)
{
    if(NULL == selfname || NULL == friendName) {
        return false;
    }
    QString data = QString("delete from friend where (id = (select id from usrInfo where name = :selfname)"
                           "and friendId = (select id from usrInfo where name = :friendName)) or "
                           "(id = (select id from usrInfo where name = :friendName)"
                           "and friendId = (select id from usrInfo where name = :selfname))");
    QSqlQuery query;
    query.prepare(data);
    query.bindValue(":selfname", selfname);
    query.bindValue(":friendName", friendName);
    if (query.exec()) {
        qDebug() << "Delete operation successful";
        qDebug() << "Rows affected:" << query.numRowsAffected();
        return true;
    } else {
        qDebug() << "Error executing delete operation:" << query.lastError().text();
        return false;
    }
}






